#coding=utf-8

"""此为python3的urllib使用"""

import urllib.request
import urllib.parse

import sys
import importlib

importlib.reload(sys)
print(sys.stdout.encoding)

def send_request():
    #输入自定义查询的关键字,python的输入是input
    keyword = input("请输入需要查询的关键字")
    #固定的url地址
    base_url = "https://www.baidu.com/s?"

    base_url__ = "https://www.google.com.hk/search?safe=strict&source=hp&ei=mQltW6O1CLe60PEP-_eY-AQ&q="
    base_url__ = base_url__ + urllib.parse.quote("二手車")  # 这里url中有中文的话, 需要将中文转换成编码字符串


    #-----------字典转查询字符串-------
    #构建查询字典,这里的键名需要去百度地址上测试找到对应的键名
    query_dict = {"wd": keyword}
    #通过urlencode方法, 按url编码转换构建查询字符串,从而能被web服务器接受
    query_str = urllib.parse.urlencode(query_dict)

    """
    # 通过urllib.unquote()方法,把url编码字符串,转换回原先字符串
    print(urllib.unquote(query_str))
    """

    #构建完整的url地址
    full_url = base_url + query_str
    #--------------请求------------------
    headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
    }
    #构建请求对象,此时没有传入data,为GET请求
    # request = urllib.request.Request(full_url, headers=headers)
    request = urllib.request.Request(full_url, headers=headers)

    #请求
    response  = urllib.request.urlopen(request)
    #响应
    return response.read()


if __name__ == '__main__':
    html = send_request()
    with open("baidu.html", "w") as f:
        f.write(html.decode("utf-8"))
